<template>
  <div class="user-list">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="searchUsers">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作栏 -->
    <el-card class="operation-card">
      <el-button type="primary" :icon="Plus" @click="openAddDialog">新增用户</el-button>
      <el-button type="danger" :icon="Delete" @click="batchDelete" :disabled="selectedUsers.length === 0">
        批量删除
      </el-button>
    </el-card>

    <!-- 用户列表 -->
    <el-card>
      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="roleNames" label="角色">
          <template #default="{ row }">
            <el-tag 
              v-for="role in row.roles" 
              :key="role.id" 
              :type="role.code === 'ADMIN' ? 'danger' : 'success'"
              style="margin-right: 5px;"
            >
              {{ role.name }}
            </el-tag>
            <span v-if="!row.roles || row.roles.length === 0">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" :icon="Edit" size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button type="success" :icon="User" size="small" @click="openRoleDialog(row)">角色</el-button>
            <el-button type="warning" :icon="Refresh" size="small" @click="resetPassword(row)">重置密码</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="deleteUser(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="saveLoading">
          {{ dialogType === 'add' ? '新增' : '更新' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="角色分配"
      width="600px"
      @close="closeRoleDialog"
    >
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username" readonly />
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox-group v-model="selectedRoleIds">
            <el-checkbox 
              v-for="role in roleList" 
              :key="role.id" 
              :label="role.id"
            >
              {{ role.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeRoleDialog">取消</el-button>
        <el-button type="primary" @click="saveUserRoles" :loading="roleLoading">
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="重置密码"
      width="400px"
      @close="closePasswordDialog"
    >
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="80px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closePasswordDialog">取消</el-button>
        <el-button type="primary" @click="savePassword" :loading="passwordLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Edit, Delete, Refresh, User } from '@element-plus/icons-vue'
import { 
  getUserPage, 
  getUserById, 
  saveOrUpdateUser, 
  deleteUsers, 
  updateUserStatus, 
  resetUserPassword, 
  getUserRoles, 
  setUserRoles 
} from '@/api/user'
import { getRoleList } from '@/api/system'

// 搜索表单
const searchForm = ref({
  username: '',
  email: '',
  status: ''
})

// 用户列表数据
const userList = ref([])
const loading = ref(false)
const selectedUsers = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框参数
const dialogVisible = ref(false)
const dialogType = ref('add')
const saveLoading = ref(false)

// 角色分配对话框
const roleDialogVisible = ref(false)
const roleLoading = ref(false)
const currentUser = ref({})
const selectedRoleIds = ref([])
const roleList = ref([])

// 重置密码对话框
const passwordDialogVisible = ref(false)
const passwordLoading = ref(false)
const passwordForm = ref({
  userId: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单数据
const form = ref({
  id: '',
  username: '',
  email: '',
  phone: '',
  password: '',
  status: 1
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 密码表单验证规则
const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const formRef = ref()
const passwordFormRef = ref()

// 加载用户列表
const loadUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm.value
    }
    const res = await getUserPage(params)
    userList.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error('Failed to load user list:', error)
  } finally {
    loading.value = false
  }
}

// 加载角色列表
const loadRoleList = async () => {
  try {
    const res = await getRoleList()
    roleList.value = res || []
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    console.error('Failed to load role list:', error)
  }
}

// 搜索用户
const searchUsers = () => {
  currentPage.value = 1
  loadUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    username: '',
    email: '',
    status: ''
  }
  currentPage.value = 1
  loadUserList()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedUsers.value = val
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadUserList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUserList()
}

// 处理状态变化
const handleStatusChange = async (row) => {
  try {
    await updateUserStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  form.value = {
    id: '',
    username: '',
    email: '',
    phone: '',
    password: '',
    status: 1
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = async (row) => {
  try {
    const res = await getUserById(row.id)
    form.value = { ...res }
    dialogType.value = 'edit'
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户详情失败')
  }
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 保存用户
const saveUser = async () => {
  try {
    await formRef.value.validate()
    saveLoading.value = true
    
    await saveOrUpdateUser(form.value)
    ElMessage.success(dialogType.value === 'add' ? '新增用户成功' : '更新用户成功')
    closeDialog()
    loadUserList()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(dialogType.value === 'add' ? '新增用户失败' : '更新用户失败')
    }
  } finally {
    saveLoading.value = false
  }
}

// 打开角色分配对话框
const openRoleDialog = async (row) => {
  try {
    currentUser.value = { ...row }
    
    // 获取用户当前角色
    const userRoles = await getUserRoles(row.id)
    selectedRoleIds.value = userRoles.map(role => role.id)
    
    // 加载角色列表
    if (roleList.value.length === 0) {
      await loadRoleList()
    }
    
    roleDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户角色失败')
    console.error('Failed to load user roles:', error)
  }
}

// 关闭角色分配对话框
const closeRoleDialog = () => {
  roleDialogVisible.value = false
  currentUser.value = {}
  selectedRoleIds.value = []
}

// 保存用户角色
const saveUserRoles = async () => {
  roleLoading.value = true
  try {
    await setUserRoles(currentUser.value.id, selectedRoleIds.value)
    ElMessage.success('角色分配成功')
    closeRoleDialog()
    loadUserList()
  } catch (error) {
    ElMessage.error('角色分配失败')
    console.error('Failed to save user roles:', error)
  } finally {
    roleLoading.value = false
  }
}

// 打开重置密码对话框
const openPasswordDialog = (row) => {
  passwordForm.value = {
    userId: row.id,
    newPassword: '',
    confirmPassword: ''
  }
  passwordDialogVisible.value = true
}

// 关闭重置密码对话框
const closePasswordDialog = () => {
  passwordDialogVisible.value = false
  passwordFormRef.value?.resetFields()
}

// 保存新密码
const savePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    await resetUserPassword(passwordForm.value.userId, passwordForm.value.newPassword)
    ElMessage.success('密码重置成功')
    closePasswordDialog()
  } catch (error) {
    ElMessage.error('密码重置失败')
    console.error('Failed to reset password:', error)
  } finally {
    passwordLoading.value = false
  }
}

// 重置密码
const resetPassword = (row) => {
  ElMessageBox.prompt('请输入新密码', '重置密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'password',
    inputValidator: (value) => {
      if (!value) {
        return '密码不能为空'
      }
      if (value.length < 6) {
        return '密码长度不能少于6位'
      }
      return true
    }
  }).then(async ({ value }) => {
    try {
      await resetUserPassword(row.id, value)
      ElMessage.success('密码重置成功')
    } catch (error) {
      ElMessage.error('密码重置失败')
      console.error('Failed to reset password:', error)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 删除用户
const deleteUser = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteUsers([row.id])
    ElMessage.success('删除用户成功')
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedUsers.value.map(item => item.id)
    await deleteUsers(ids)
    ElMessage.success('批量删除用户成功')
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除用户失败')
    }
  }
}

// 初始化加载
onMounted(() => {
  loadUserList()
  loadRoleList()
})
</script>

<style scoped>
.user-list {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    width: 100%;
  }
}
</style>